package com.edgclub.edg.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.chat.EMClient;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 频道切换
 */
public class MessageFragment extends GzBaseFragment implements View.OnClickListener {

    private FrameLayout mChat;
    private RadioButton mChat_redio, mReply_redio;
    private TextView mLine1;
    private TextView unreadLabel;
    private FrameLayout mReply;
    private TextView mLine2;
    private android.support.v4.view.ViewPager mViewpager2;
    private MyPagerAdapter myPagerAdapter;
    private ArrayList<Fragment> fragmentList = new ArrayList<>();
    ;
    private UserPrefUtils userPrefUtils;

    private LinearLayout layout_empty;
    private TextView text_empty;
    private ImageView imageView_empty;

    private RadioButton radio_report;
    private TextView line3;
    private TextView unreadLabe3;
    private FrameLayout report;

    private boolean isReport;

    public static MessageFragment newInstance(String text) {
        MessageFragment f = new MessageFragment();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message_main, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userPrefUtils = new UserPrefUtils(getActivity());
        isReport = userPrefUtils.isReportTopic();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }


    private void initView(View view) {
        mChat = (FrameLayout) view.findViewById(R.id.chat);
        unreadLabel = (TextView) view.findViewById(R.id.unreadLabel);
        mLine1 = (TextView) view.findViewById(R.id.line1);
        mReply = (FrameLayout) view.findViewById(R.id.reply);
        mLine2 = (TextView) view.findViewById(R.id.line2);
        mChat_redio = (RadioButton) view.findViewById(R.id.radio_chat);
        mReply_redio = (RadioButton) view.findViewById(R.id.radio_reply);
        mViewpager2 = (android.support.v4.view.ViewPager) view.findViewById(R.id.viewpager2);
        mChat.setOnClickListener(this);
        mReply.setOnClickListener(this);
        mChat_redio.setOnClickListener(this);
        mReply_redio.setOnClickListener(this);

        layout_empty = (LinearLayout) view.findViewById(R.id.layout_empty);
        text_empty = (TextView) view.findViewById(R.id.text_empty);
        imageView_empty = (ImageView) view.findViewById(R.id.imageView_empty);
        text_empty.setText("你还没收到任何消息");
        imageView_empty.setImageResource(R.drawable.nomess);

        radio_report = (RadioButton) view.findViewById(R.id.radio_report);
        line3 = (TextView) view.findViewById(R.id.line3);
        unreadLabe3 = (TextView) view.findViewById(R.id.unreadLabe3);
        report = (FrameLayout) view.findViewById(R.id.report);
        report.setOnClickListener(this);
        radio_report.setOnClickListener(this);
    }


    private void initData() {
        if (isReport) {
            report.setVisibility(View.VISIBLE);
        } else {
            report.setVisibility(View.GONE);
        }

        myPagerAdapter = new MyPagerAdapter(getChildFragmentManager());
        fragmentList.add(ChatListFragment.newInstance("mess"));
        fragmentList.add(ReplyFragment.newInstance("huifu"));
        myPagerAdapter.setFragmentList(fragmentList);
        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources()
                .getDisplayMetrics());
        mViewpager2.setPageMargin(pageMargin);
        mViewpager2.setOffscreenPageLimit(3);
        mViewpager2.setAdapter(myPagerAdapter);
        mViewpager2.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                try {
                    refreshReplyList();
                    refreshReportList();
                    switch (position) {
                        case 0:
                            mChat_redio.setChecked(true);
                            mReply_redio.setChecked(false);
                            radio_report.setChecked(false);
                            mLine1.setVisibility(View.VISIBLE);
                            mLine2.setVisibility(View.GONE);
                            line3.setVisibility(View.GONE);
                            break;
                        case 1:
                            mChat_redio.setChecked(false);
                            mReply_redio.setChecked(true);
                            radio_report.setChecked(false);
                            mLine1.setVisibility(View.GONE);
                            mLine2.setVisibility(View.VISIBLE);
                            line3.setVisibility(View.GONE);
                            break;
                        case 2:
                            mChat_redio.setChecked(false);
                            mReply_redio.setChecked(false);
                            radio_report.setChecked(true);
                            mLine1.setVisibility(View.GONE);
                            mLine2.setVisibility(View.GONE);
                            line3.setVisibility(View.VISIBLE);
                            break;
                    }

                    setShow(position);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        refreshReplyList();
        refreshReportList();
        if (GuZhiApplication.getInstance().isFirstNew) {
            mViewpager2.setCurrentItem(1);
            GuZhiApplication.getInstance().isFirstNew = false;
        } else if (GuZhiApplication.getInstance().isReportNew) {
            mViewpager2.setCurrentItem(2);
            GuZhiApplication.getInstance().isReportNew = false;
        } else {
            mViewpager2.setCurrentItem(0);
            setShow(0);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.radio_chat:
            case R.id.chat:
                mChat_redio.setChecked(true);
                mReply_redio.setChecked(false);
                radio_report.setChecked(false);
                mLine1.setVisibility(View.VISIBLE);
                mLine2.setVisibility(View.GONE);
                line3.setVisibility(View.GONE);
                mViewpager2.setCurrentItem(0);
                break;
            case R.id.radio_reply:
            case R.id.reply:
                mChat_redio.setChecked(false);
                mReply_redio.setChecked(true);
                radio_report.setChecked(false);
                mLine1.setVisibility(View.GONE);
                mLine2.setVisibility(View.VISIBLE);
                line3.setVisibility(View.GONE);
                mViewpager2.setCurrentItem(1);
                break;
            case R.id.radio_report:
            case R.id.report:
                mChat_redio.setChecked(false);
                mReply_redio.setChecked(false);
                radio_report.setChecked(true);
                mLine1.setVisibility(View.GONE);
                mLine2.setVisibility(View.GONE);
                line3.setVisibility(View.VISIBLE);
                mViewpager2.setCurrentItem(2);
                break;
        }
    }


    public class MyPagerAdapter extends FragmentPagerAdapter {

        ArrayList<Fragment> fragmentList;

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "";
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }


        public void setFragmentList(ArrayList<Fragment> fragmentList) {
            this.fragmentList = fragmentList;
        }
    }

    @Override
    public void onHiddenChanged(boolean isVisibleToUser) {
        super.onHiddenChanged(isVisibleToUser);
        if (fragmentList.size() == 2) {
            refreshReplyList();
            ((ReplyFragment) fragmentList.get(1)).setTip();
        }
    }

    public void refreshChatList(String imid, int type) {
        if (fragmentList.size() == 1) {
            ((ChatListFragment) fragmentList.get(0)).refresh_mian(imid, type);
        }
        if (null != mViewpager2 && mViewpager2.getCurrentItem() == 0) {
            setShow(0);
        }
    }

    public void refreshReplyList() {
        if (null != mViewpager2 && mViewpager2.getCurrentItem() == 1 && userPrefUtils.getMessTip()) {
            unreadLabel.setVisibility(View.GONE);
            userPrefUtils.saveMessTip(false);
            if (fragmentList.size() == 2) {
                ((ReplyFragment) fragmentList.get(1)).setTip();
            }
        } else {
            if (null != userPrefUtils && userPrefUtils.getMessTip()) {
                (getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        unreadLabel.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }

    public void refreshReportList() {
            if (null != userPrefUtils && userPrefUtils.getReportTip()) {
                (getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        unreadLabe3.setVisibility(View.VISIBLE);
                    }
                });
            }
    }

    public void setCurrent(int page) {
        if (page == 1 && mViewpager2.getCurrentItem() == 1) {
            refreshReplyList();
            userPrefUtils.saveMessTip(false);
            mChat_redio.setChecked(false);
            mReply_redio.setChecked(true);
            radio_report.setChecked(false);
            mLine1.setVisibility(View.GONE);
            mLine2.setVisibility(View.VISIBLE);
            line3.setVisibility(View.GONE);
            mViewpager2.setCurrentItem(1);
        } else if (page == 1 && mViewpager2.getCurrentItem() == 2) {
            refreshReportList();
            userPrefUtils.saveReportTip(false);
            mChat_redio.setChecked(false);
            mReply_redio.setChecked(false);
            radio_report.setChecked(true);
            mLine1.setVisibility(View.GONE);
            mLine2.setVisibility(View.GONE);
            line3.setVisibility(View.VISIBLE);
            mViewpager2.setCurrentItem(2);
        } else {
            mChat_redio.setChecked(true);
            mReply_redio.setChecked(false);
            radio_report.setChecked(false);
            mLine1.setVisibility(View.VISIBLE);
            mLine2.setVisibility(View.GONE);
            line3.setVisibility(View.GONE);
            mViewpager2.setCurrentItem(0);
            refreshChatList("", 0);
        }
    }

    private boolean show1, show2, show3 = false;

    @Subscribe
    public void refreshListView(HashMap<String, Object> map) {
        String event = (String) map.get("event");
        if (null != event && BroadCastEvent.CHATLIST_NOMESS.equals(event)) {
            boolean isShow = (boolean) map.get("obj");
            int key = (int) map.get("key");
            if (key == mViewpager2.getCurrentItem()) {
                if (isShow) {
                    layout_empty.setVisibility(View.GONE);
                } else {
                    layout_empty.setVisibility(View.VISIBLE);
                }
            }
            if (key == 1) {
                show2 = isShow;
            } else if (key == 2){
                show3 = isShow;
            }else {
                show1 = isShow;
            }
        }
    }

    private void setShow(int current) {
        switch (current) {
            case 0:
                int num = EMClient.getInstance().chatManager().getAllConversations().size();
                if (num > 0) {
                    show1 = true;
                } else {
                    show1 = false;
                }
                if (show1) {
                    layout_empty.setVisibility(View.GONE);
                } else {
                    layout_empty.setVisibility(View.VISIBLE);
                }
                break;
            case 1:
                if (show2) {
                    layout_empty.setVisibility(View.GONE);
                } else {
                    layout_empty.setVisibility(View.VISIBLE);
                }
                break;
            case 2:
                if (show3) {
                    layout_empty.setVisibility(View.GONE);
                } else {
                    layout_empty.setVisibility(View.VISIBLE);
                }
                break;
        }

    }
}
